package com.zlm.design.observer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zlm
 * @date 2025/5/23
 */
public class TVStation {

    private final List<EventListener> eventListeners = new ArrayList<>();

    private final Map<Class<? extends Event>,List<EventListener>> eventListenerMap = new HashMap<>();

    //订阅消息
    public void subscribe(EventListener listener,Class<? extends Event> eventClass) {
        //eventListeners.add(listener);
        eventListenerMap.computeIfAbsent(eventClass,k->new ArrayList<>()).add(listener);
    }

    //发布消息
    public void publish(Event event){
        Class<? extends Event> aClass = event.getClass();
        List<EventListener> listeners = eventListenerMap.get(aClass);
        if(listeners!=null){
            for(EventListener listener : listeners){
                listener.onEvent(event);
            }
        }
    }

}
